package com.icode.gulimall.ware.service.impl;


import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.icode.common.constant.WareConstant;
import com.icode.gulimall.ware.entity.PurchaseDetailEntity;
import com.icode.gulimall.ware.service.PurchaseDetailService;
import com.icode.gulimall.ware.service.WareInfoService;
import com.icode.gulimall.ware.service.WareSkuService;
import com.icode.gulimall.ware.vo.MergeVo;
import com.icode.gulimall.ware.vo.PurchaseFinishVo;
import com.icode.gulimall.ware.vo.PurchaseItemDoneVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.icode.common.utils.PageUtils;
import com.icode.common.utils.Query;

import com.icode.gulimall.ware.dao.PurchaseDao;
import com.icode.gulimall.ware.entity.PurchaseEntity;
import com.icode.gulimall.ware.service.PurchaseService;
import org.springframework.transaction.annotation.Transactional;

import javax.validation.constraints.NotNull;


@Service("purchaseService")
public class PurchaseServiceImpl extends ServiceImpl<PurchaseDao, PurchaseEntity> implements PurchaseService {

    @Autowired
    PurchaseDetailService purchaseDetailService;

    @Autowired
    WareSkuService wareSkuService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<PurchaseEntity> page = this.page(
                new Query<PurchaseEntity>().getPage(params),
                new QueryWrapper<PurchaseEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public PageUtils queryUnReceivePage(Map<String, Object> params) {

        IPage<PurchaseEntity> page = this.page(
                new Query<PurchaseEntity>().getPage(params),
                new QueryWrapper<PurchaseEntity>().eq("status", 0).or().eq("status", 1)
        );

        return new PageUtils(page);
    }

    @Transactional
    @Override
    public void saveMergePurchase(MergeVo vo) {
        //保存合并的采购单
        Long purchaseId = vo.getPurchaseId();
        if (purchaseId == null) {
            PurchaseEntity purchase = new PurchaseEntity();
            purchase.setCreateTime(new Date());
            purchase.setUpdateTime(new Date());
            purchase.setStatus(WareConstant.PurchaseStatusEnum.CREATED.getCode());
            this.save(purchase);
            purchaseId = purchase.getId();
        }
        //TODO 判断采购单的状态
        if (purchaseId >= 2) {
            try {
                throw new Exception("判断采购单的状态必须是0、1");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        PurchaseEntity purchase = this.getById(purchaseId);
        //获得商品价格
        List<Integer> items = vo.getItems();
        BigDecimal price = new BigDecimal(0);
        List<PurchaseDetailEntity> listByIds = purchaseDetailService.listByIds(items);
        for (PurchaseDetailEntity purchaseDetail : listByIds) {
            BigDecimal skuPrice = purchaseDetail.getSkuPrice();
            BigDecimal skuNum = new BigDecimal(purchaseDetail.getSkuNum());
            BigDecimal multiply = skuPrice.multiply(skuNum);
            price = price.add(multiply);
        }
        purchase.setUpdateTime(new Date());
        purchase.setAmount(price);
        this.update(purchase, new UpdateWrapper<PurchaseEntity>().eq("id", purchase.getId()));

        //更新PurchaseDetailEntity的purchaseId和status
        Long finalPurchaseId = purchaseId;
        List<PurchaseDetailEntity> collect = listByIds.stream().map(entity -> {
            PurchaseDetailEntity purchaseDetailEntity = new PurchaseDetailEntity();
            purchaseDetailEntity.setPurchaseId(finalPurchaseId);
            purchaseDetailEntity.setId(entity.getId());
            purchaseDetailEntity.setStatus(WareConstant.PurchaseDetailStatusEnum.ASSIGNED.getCode());
            return purchaseDetailEntity;
        }).collect(Collectors.toList());
        purchaseDetailService.updateBatchById(collect);
    }

    @Transactional
    @Override
    public void received(List<Long> ids) {
        //更新采购单
        //1）、状态：已领取   2）、更新时间：new Date()
        List<PurchaseEntity> purchaseEntities = this.baseMapper.selectBatchIds(ids).stream()
                .filter(Entity -> Entity.getStatus() < 2)
                .collect(Collectors.toList()
                );
        List<PurchaseEntity> collect = purchaseEntities.stream().map(item -> {
            item.setStatus(WareConstant.PurchaseStatusEnum.RECEIVE.getCode());
            item.setUpdateTime(new Date());
            return item;
        }).collect(Collectors.toList());
        this.updateBatchById(collect);
        //更新采购需求的状态：正在采购
        List<PurchaseDetailEntity> purchaseDetailEntityList = purchaseDetailService.list(new QueryWrapper<PurchaseDetailEntity>()
                .in("purchase_id", ids)).stream()
                .filter(Entity -> Entity.getStatus() < 2)
                .collect(Collectors.toList()
                );
        List<PurchaseDetailEntity> detailEntities = purchaseDetailEntityList.stream().map(item -> {
            item.setStatus(WareConstant.PurchaseDetailStatusEnum.BUYING.getCode());
            return item;
        }).collect(Collectors.toList());
        purchaseDetailService.updateBatchById(detailEntities);
    }

    @Transactional
    @Override
    public void done(PurchaseFinishVo doneVo) {
        @NotNull Long id = doneVo.getId();

        //1.改变采购项的状态
        Boolean flag = true;
        List<PurchaseItemDoneVo> items = doneVo.getItems();
        List<PurchaseDetailEntity> updates = new ArrayList<>();
        for(PurchaseItemDoneVo item:items){
            PurchaseDetailEntity purchaseDetailEntity = purchaseDetailService.getById(item.getItemId());
            if (item.getStatus()== WareConstant.PurchaseDetailStatusEnum.FINISH.getCode()){
                flag = false;
                purchaseDetailEntity.setStatus(WareConstant.PurchaseDetailStatusEnum.HASERROR.getCode());
            } else {
                purchaseDetailEntity.setStatus(WareConstant.PurchaseDetailStatusEnum.FINISH.getCode());
                //3.将成功采购进行入库
                PurchaseDetailEntity entity = purchaseDetailService.getById(item.getItemId());
                wareSkuService.addStock(entity.getSkuId(), entity.getWareId(), entity.getSkuNum());
            }
            purchaseDetailEntity.setId(item.getItemId());
            updates.add(purchaseDetailEntity);
        }
        purchaseDetailService.updateBatchById(updates);

        //2.改变采购单的状态
        PurchaseEntity purchaseEntity = new PurchaseEntity();
        purchaseEntity.setId(id);
        purchaseEntity.setStatus(flag?WareConstant.PurchaseStatusEnum.FINISH.getCode():WareConstant.PurchaseStatusEnum.HASERROR.getCode());
        purchaseEntity.setUpdateTime(new Date());
        this.updateById(purchaseEntity);
    }
}